package com.Sake.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author zsh
 * @date 2021.7.1
 */
@Component
public class MultipartFileToFileUtil {

    private static final Logger logger = LoggerFactory.getLogger(MultipartFileToFileUtil.class);

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.getOriginalFilename() == null) {
            logger.error("file.getOriginalFilename()为空 异常");
            return toFile;
        }
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }


    /**
     * 获取流文件
     *
     * @param ins  输入流
     * @param file 文件
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void close(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    /**
     * 重命名文件
     *
     * @param file    需要重命名的文件
     * @param newName 新名字
     */
    public static File rename(File file, String newName) throws FileNotFoundException {
        String absolutePath = file.getAbsolutePath();
        String substring = absolutePath.substring(0, absolutePath.lastIndexOf("\\"));
        String tail = absolutePath.substring(absolutePath.lastIndexOf("."));
        File newFile = new File(substring + newName + tail);
        FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
        MultipartFileToFileUtil.inputStreamToFile(inputStream,newFile);
        return newFile;
//        boolean chang = file.renameTo(newFile);
//        if (chang) {
//            return newFile;
//        }
//        logger.error("重命名文件失败 返回原文件");
//        return file;
    }

}
